import { useDataStore } from "@/store";
import { IOptionItem } from "@/types";

/*
 * @Description:
 * @Author: 胡涛
 * @Date: 2023-09-05 23:46:05
 * @LastEditors: 胡涛
 * @LastEditTime: 2024-01-21 21:25:01
 */

/**
 * 生字生成下拉选项数据
 * @param name
 * @param emptyItem
 * @returns
 */
const dictionaryOptions = (
  name: string,
  emptyItem?: { name: string; value: string | number }
) => {
  const dataStore = useDataStore();
  let item = dataStore.dictionaryItems.find((x) => x.code == name);
  if (!item) {
    return [];
  }
  let items: Array<IOptionItem> = item.items.map((x) => {
    return { label: x.name, value: x.value };
  });
  if (emptyItem?.value) {
    items.splice(0, 0, {
      label: emptyItem.name,
      value: emptyItem.value,
    });
  }
  return items;
};

/**
 * 根据键名获取数据字典项列表
 * @param name 
 * @returns 
 */
const getDictionaryItems = (name: string) => {
  const dataStore = useDataStore();
  let item = dataStore.dictionaryItems.find((x) => x.code == name);
  return item.items || []
}

/**
 * 字典格式显示名称
 * @param name
 * @param value
 * @returns
 */
const dictionaryName = (
  name: string,
  value: string | number | Array<string | number>
) => {
  const dataStore = useDataStore();
  let item = dataStore.dictionaryItems.find((x) => x.code == name);
  if (!item) {
    return "";
  }
  if (Array.isArray(value)) {
    return item.items
      .filter((x) => value.findIndex((val) => val == x.value))
      .map((x) => x.name)
      .join(",");
  } else {
    return item.items.find((x) => x.value == value)?.name || "";
  }
};

export { dictionaryName, dictionaryOptions, getDictionaryItems };
